#include <bluetooth/bluetooth.h>
#include <bluetooth/hci.h>
#include <bluetooth/hci_lib.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/ioctl.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
	int id = hci_get_route(NULL);
	printf("id=%d\n");
	int sock = hci_open_dev(id);
	printf("sock=%08x\n");

	int ctl = socket(AF_BLUETOOTH, SOCK_RAW, BTPROTO_HCI);
	if( ctl < 0 ){
		printf("cnat open hci socket\n");
		return -1;
	}

	hci_dev_list_req *dl;
	hci_dev_req *dr;
	hci_dev_info di;
	
	dl = (hci_dev_list_req *)new char[HCI_MAX_DEV * sizeof(hci_dev_req) + sizeof(uint16_t)];
	dl->dev_num = HCI_MAX_DEV;
	dr = dl->dev_req;
		
	if( ioctl(ctl, HCIGETDEVLIST, (void *)dl) < 0 ){
		printf("can't get dedevice list\n");
		return -2;
	}
	
	printf("%d devices\n", dl->dev_num);
	if( dl->dev_num > 0 ){
		for( int i = 0; i < dl->dev_num; ++i ){
			di.dev_id = (dr + i)->dev_id;
			ioctl(ctl, HCIGETDEVINFO, (void *)&di);
			printf("id=%d name: %s\n", di.dev_id, di.name);
		}
	}
	else{
		di.dev_id = 0;
		if( ioctl(ctl, HCIGETDEVINFO, (void *)&di) < 0 ){
			printf("HCIGETDEVINFO failed\n");
		}
		printf("id=%d name: %s\n", di.dev_id, di.name);		
	}	
	
	while(1){
		di.dev_id = 0;
		ioctl(ctl, HCIGETDEVINFO, (void *)&di);
		printf("acl packets=%8d sco packets=%8d\n", di.acl_pkts, di.sco_pkts);
	}	
	close(ctl);
	return 0;
}
